package com.ruihang.generalibrary.ui.util;

import android.support.annotation.IdRes;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.fragment.BaseGeneraFragment;
import com.ruihang.generalibrary.utils.OtherUtils;

/**
 * Created by Administrator on 2017/3/24.
 */

public class CustomFragmentChangeHelper<T extends BaseGeneraFragment> {
    private T showingFragment;
    @IdRes
    private int contentId;

    private int tagCount = 1;

    public CustomFragmentChangeHelper(int contentId) {
        this.contentId = contentId;
    }

    public void showFragment(T fragment, FragmentManager fragmentManager) {
        if (fragment == null || showingFragment == fragment) {
            JLog.e("show fragment faile fragment :" + fragment + "  showingFragment:" + showingFragment);
            return;
        }
        FragmentTransaction ft = fragmentManager.beginTransaction();
        if (showingFragment != null && showingFragment.isAdded()) {
            ft.hide(showingFragment);
            showingFragment.onToHided();
        }
        if (fragment.isAdded()) {
            ft.show(fragment);
        } else {
            ft.add(contentId, fragment);
        }
        ft.commit();
        showingFragment = fragment;
        JLog.e("show fragment->" + fragment);
    }

    public T getFragmentByTag(FragmentManager fragmentManager, int pos) {
        String tag = OtherUtils.makeFragmentName(contentId, getNamePos(pos));
        return (T) fragmentManager.findFragmentByTag(tag);
    }

    public void showFragment(T fragment, FragmentManager fragmentManager, int pos) {
        showFragment(fragment, fragmentManager, OtherUtils.makeFragmentName(contentId, getNamePos(pos)));
    }

    private void showFragment(T fragment, FragmentManager fragmentManager, String tag) {
//        if (!AndroidUtil.isNetworkConnected(MainActivity.this)) {
//            toast(R.string.networkFail);
//            return;
//        }
        if (fragment == null || showingFragment == fragment) {
            JLog.e("show fragment faile fragment :" + fragment + "  showingFragment:" + showingFragment);
            return;
        }
        FragmentTransaction ft = fragmentManager.beginTransaction();
        if (showingFragment != null && showingFragment.isAdded()) {
            ft.hide(showingFragment);
            showingFragment.onToHided();
        }
        if (fragment.isAdded()) {
            ft.show(fragment);
        } else {
            ft.add(contentId, fragment, tag);
        }
//        ft.commit();
        ft.commitNowAllowingStateLoss();
        showingFragment = fragment;
        JLog.e("show fragment->" + fragment);

    }

    private int getNamePos(int pos) {
        return pos % tagCount + 1;
    }

    public T getShowingFragment() {
        return showingFragment;
    }
}
